//
//  AQWifiConfig.m
//  AQ800
//
//  Created by 赵武 on 13-12-9.
//  Copyright (c) 2013年 杭州茂葳科技有限公司. All rights reserved.
//

#import "AQWifiConfig.h"

@interface AQWifiConfig()
{
    // 全局变量
    GCDAsyncUdpSocket *m_udp;
    NSUInteger m_port;
    NSString *m_gwip;
    NSThread *m_ts;
    NSString *m_lock1;
    NSMutableArray *m_pack;
    BOOL isStop;
}
@end

// Wifi配置功能类
@implementation AQWifiConfig

// 初始化
- (id)init
{
    m_port = 15150;
    m_gwip = nil;
    m_ts = nil;
    m_lock1 = @"AQWifiConfig_lock1";
    m_pack = nil;
    isStop = NO;
    return [super init];
}

// 构建数据
- (NSMutableArray *)MakeData:(char *)data datalen:(NSUInteger)datalen type:(char)type
{
    // 格式化包
    NSMutableArray *marr = [[NSMutableArray alloc]init];
    if ( datalen == 0 )
    {
        datalen = 1;
    }
    unsigned char packdata[datalen + 4];
    packdata[0] = (datalen + 4) & 0xff;
    packdata[1] = type;
    memcpy(&packdata[2], data, datalen);
    packdata[datalen + 2] = 0x00;
    unsigned char sum = 0;
    for (int i=0; i<(datalen+2); i++)
    {
        sum += packdata[i];
    }
    packdata[datalen + 3] = sum & 0xff;
    // 包编码
    unsigned char count = 0;
    unsigned char prevValue = 0;
    NSNumber *start1 = [NSNumber numberWithInteger:1121];
    NSNumber *start2 = [NSNumber numberWithInteger:1113];
    [marr addObject:start1];
    [marr addObject:start2];
    for (int i=0; i<(datalen+4); i++)
    {
        unsigned char bh = packdata[i] >> 4 & 0x0f;
        unsigned char bl = packdata[i] & 0x0f;
        NSUInteger value2 = (((count ^ prevValue) << 4) | (bh & 0x0f)) + 600;
        NSNumber *value1 = [NSNumber numberWithInteger:value2];
        [marr addObject:value1];
        count ++;
        prevValue = bh;
        value2 = (((count ^ prevValue) << 4) | (bl & 0x0f)) + 600;
        value1 = [NSNumber numberWithInteger:value2];
        [marr addObject:value1];
        count ++;
        prevValue = bl;
        count %= 16;
    }
    return marr;
}

// 构建数据包
- (NSMutableArray *)MakePacket:(NSString *)ssid key:(NSString *)key
{
    if ( [ssid length] == 0 ) return nil;
    // 获取ssid和key的字节集
    char bkey[128] = {0};
    char bssid[128] = {0};
    NSUInteger ssid_len = 0;
    NSUInteger key_len = 0;
    NSRange range;
    range.length = [ssid length];
    range.location = 0;
    [ssid getBytes:bssid maxLength:128 usedLength:&ssid_len encoding:NSUTF8StringEncoding
           options:0 range:range remainingRange:NULL];
    if ( [key length] != 0 )
    {
        range.length = [key length];
        range.location = 0;
        [key getBytes:bkey maxLength:128 usedLength:&key_len encoding:NSUTF8StringEncoding
              options:0 range:range remainingRange:NULL];
    }
    // 构建数据
    NSMutableArray *marr = [[NSMutableArray alloc] init];
    [marr addObjectsFromArray:[self MakeData:bssid datalen:ssid_len type:0x02]];
    [marr addObjectsFromArray:[self MakeData:bkey datalen:key_len type:0x04]];
    return marr;
}

// 发送线程
- (void)ts_run
{
    return ;
}

// 发送线程
- (void)ts_run2
{
    @synchronized(m_lock1)
    {
        m_udp = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        NSError *error = nil;
        if (![m_udp bindToPort:0 error:&error])
        {
            [m_udp close];
            return;
        }
        [m_udp enableBroadcast:YES error:nil];
        [m_udp setIPv4Enabled:YES];
        
        char databuf[2048] = {0};
        long tag = 0;
        ESPUDPSocketClient * client = [[ESPUDPSocketClient alloc]init];
        NSMutableArray * sendArray = [[NSMutableArray alloc] init];
        
        isStop = NO;
        while (!isStop)
        {
            tag = 0;
            usleep(200*1000);
            if([sendArray count] == 0)
            {
                for (int i=0; i<m_pack.count; i++)
                {
                    tag ++;
                    NSInteger len = [(NSNumber *)[m_pack objectAtIndex:i] integerValue];
                    NSData *data = [[NSData alloc]initWithBytes:databuf length:len];
//                [m_udp sendData:data toHost:m_gwip port:m_port withTimeout:-1 tag:tag];
                                    [sendArray addObject:data];
                }
            
            }
            
            [client sendDataWithBytesArray2:sendArray ToTargetHostName:m_gwip WithPort:m_port andInterval:0];
            
        }
        [m_udp close];
        [client close];
        NSLog(@"WIFI配置发送线程退出");
    }
}

// 开启发送
- (BOOL)Start:(NSString *)ssid key:(NSString *)key gwip:(NSString *)gwip
{
    // 首先退出之前未完成的线程
    [self Stop];
    
    @synchronized(m_lock1)
    {
        // 如果发送地址为空则返回失败
        if (gwip == nil)
        {
            return NO;
        }
        // 构建包
        [m_pack removeAllObjects];
        m_pack = nil;
        
        m_pack = [self MakePacket:ssid key:key];
        // 启动线程发送包
        m_gwip = gwip;
//        [self ts_run2];
//        static dispatch_once_t onceToken;
        __weak AQWifiConfig *that = self;
        dispatch_queue_t queue = dispatch_queue_create("com.itboye.aq", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            [that ts_run2];
        });
//        m_ts = [[NSThread alloc] initWithTarget:self selector:@selector(ts_run2) object:nil];
//        [m_ts start];
    }
    //[self performSelectorInBackground:@selector(ts_run) withObject:nil];
    return YES;
}

// 停止发送
- (BOOL)Stop
{
    
    isStop = YES;
    if ( m_ts != nil )
    {
        [m_ts cancel];
        
        return YES;
    }
    return NO;
}

@end
